package no.cicero.testframework.xml.usecase;

import no.cicero.testframework.common.xml.XmlImporter;
import no.cicero.testframework.common.xml.XmlTag;
import no.cicero.testframework.model.usecase.UseCase;
import no.cicero.testframework.xml.IXmlNameTable;
import no.cicero.testframework.xml.XmlImporterValidation;
import org.xml.sax.SAXException;

import javax.xml.parsers.SAXParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class UseCaseImporter extends XmlImporterValidation implements IXmlNameTable.IUseCaseTag{
    private final static String SCHEMA_FILE = "ucSchema.xsd";

    private UseCase useCase = null;
    public UseCase getUseCase() { return useCase; }

    public UseCaseImporter(SAXParser p){
        super(p, SCHEMA_FILE);
    }

    public UseCase doImport(String servicePath) throws SAXException, IOException {
		return doImport(new File(servicePath));
    }

    public UseCase doImport(File servicePath) throws SAXException, IOException {
        useCase = null;

        validateStream(new FileInputStream(servicePath));

        super.doImport(new FileInputStream(servicePath));
        return useCase;
    }

    public UseCase doImportFromStream(InputStream is) throws SAXException, IOException {
        useCase = null;
        // no valiation

        super.doImport( is );

        return useCase;
    }

    //----interface IXmlImporter
    @Override
    public void handleStartElement(XmlImporter importer, XmlTag tag) throws SAXException {
        if( tag.getName().equalsIgnoreCase( ROOT_ELEMENT ) ) {
            useCase = new UseCase();
        }
    }

    @Override
    public void handleText(XmlImporter importer, XmlTag tag, String text) throws SAXException {
         if(tag.getParent().getName().equalsIgnoreCase(ROOT_ELEMENT)){
            if(tag.getName().equalsIgnoreCase( SHORT_DESCRIPTION_ELEMENT ) ) {
                useCase.setShortDescription(text);
            }
            else if(tag.getName().equalsIgnoreCase( DESCRIPTION_ELEMENT ) ) {
                useCase.setDescription(text);
            }
            else if(tag.getName().equalsIgnoreCase( LOCATION_ELEMENT ) ) {
                useCase.setTestCasesLocation(text);
            }
        } else if( tag.getParent().getName().equalsIgnoreCase(FILES_ELEMENT) && tag.getName().equalsIgnoreCase( IXmlNameTable.IUseCaseFilesTag.FILE_ELEMENT ) ) {
            useCase.addTestCase(text);
        }
    }

}